import request from '@/utils/http'
import { BaseResponse } from './common'

// 购物车状态枚举
export type CartStatus = 'active' | 'inactive' | 'expired'

// 商品类型枚举
export type ProductType = 'vip' | 'ticket' | 'physical'

// 商品状态枚举
export type ProductStatus = 'active' | 'inactive'

// 商品信息（购物车中关联的商品信息）
export interface ProductInfo {
  _id: string
  name: string
  description: string
  price: number // 价格（分）
  type: ProductType
  status: ProductStatus
  image: string
}

// 购物车项实体
export interface CartItem {
  _id?: string
  openid: string // 用户openid
  productId: string // 商品ID
  quantity: number // 商品数量
  price: number // 商品价格（分）
  status: CartStatus // 购物车状态
  createTime: number // 创建时间（秒级时间戳）
  updateTime: number // 更新时间（秒级时间戳）
  product?: ProductInfo // 关联的商品信息
  // 扩展字段 - 用于前端显示
  statusText?: string
  formattedCreateTime?: string
  formattedUpdateTime?: string
  totalAmount?: number // 总金额（分）
  userNickName?: string // 用户昵称（从用户表获取）
}

// 购物车列表查询参数
export interface CartListParams {
  page?: number
  size?: number
  sort?: string
  order?: 'asc' | 'desc'
  openid?: string // 用户openid过滤
  productId?: string // 商品ID过滤
  status?: CartStatus // 状态过滤
  keyword?: string // 关键字搜索（用户openid）
}

// 购物车列表响应
export interface CartListResponse {
  data: CartItem[]
  total: number
  code: number
  message: string
}

// 通用响应消息
export interface CartActionResponse {
  message: string
}

export class CartService {
  // 获取购物车列表
  static getCartList(params?: CartListParams) {
    return request.get<BaseResponse<CartItem[]>>({
      url: '/api/v1/admin/cart/list',
      params
    })
  }

  // 获取购物车项详情
  static getCartDetail(id: string) {
    return request.get<BaseResponse<CartItem>>({
      url: `/api/v1/admin/cart/detail/${id}`
    })
  }

  // 获取用户购物车列表
  static getUserCart(openid: string) {
    return request.get<BaseResponse<CartItem[]>>({
      url: `/api/v1/admin/cart/user/${openid}`
    })
  }
}

// 工具函数

// 获取购物车状态文本
export const getCartStatusText = (status: CartStatus): string => {
  const texts: Record<CartStatus, string> = {
    active: '有效',
    inactive: '无效',
    expired: '过期'
  }
  return texts[status] || status
}

// 获取购物车状态标签类型
export const getCartStatusTagType = (status: CartStatus): string => {
  const types: Record<CartStatus, string> = {
    active: 'success',
    inactive: 'warning',
    expired: 'danger'
  }
  return types[status] || 'info'
}

// 获取商品类型文本
export const getProductTypeText = (type: ProductType): string => {
  const texts: Record<ProductType, string> = {
    vip: 'VIP会员',
    ticket: '入场券',
    physical: '实物商品'
  }
  return texts[type] || type
}

// 获取商品类型标签类型
export const getProductTypeTagType = (type: ProductType): string => {
  const types: Record<ProductType, string> = {
    vip: 'warning',
    ticket: 'success',
    physical: 'primary'
  }
  return types[type] || 'info'
}

// 获取商品状态文本
export const getProductStatusText = (status: ProductStatus): string => {
  const texts: Record<ProductStatus, string> = {
    active: '启用',
    inactive: '禁用'
  }
  return texts[status] || status
}

// 获取商品状态标签类型
export const getProductStatusTagType = (status: ProductStatus): string => {
  const types: Record<ProductStatus, string> = {
    active: 'success',
    inactive: 'info'
  }
  return types[status] || 'info'
}

// 格式化金额（分转元）
export const formatAmount = (amount: number): string => {
  return `¥${(amount / 100).toFixed(2)}`
}

// 计算总金额
export const calculateTotalAmount = (price: number, quantity: number): number => {
  return price * quantity
}

// 格式化时间
export const formatDate = (timestamp?: number): string => {
  if (!timestamp) return '-'

  try {
    const date = new Date(timestamp * 1000)
    if (isNaN(date.getTime())) {
      return timestamp.toString()
    }

    return date
      .toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      })
      .replace(/\//g, '-')
  } catch (error) {
    console.error('时间格式化错误:', error, timestamp)
    return timestamp?.toString() || '-'
  }
}

// 判断购物车项是否有效
export const isCartItemValid = (item: CartItem): boolean => {
  return item.status === 'active' && item.product?.status === 'active'
}

// 判断是否可以操作购物车项
export const canOperateCartItem = (item: CartItem): boolean => {
  return item.status !== 'expired'
}

// 获取购物车状态优先级（用于排序）
export const getCartStatusPriority = (status: CartStatus): number => {
  const priorities: Record<CartStatus, number> = {
    active: 1,
    inactive: 2,
    expired: 3
  }
  return priorities[status] || 4
}

// 格式化商品信息
export const formatProductInfo = (product?: ProductInfo): string => {
  if (!product) return '-'
  return `${product.name} (${getProductTypeText(product.type)})`
}

// 格式化用户信息
export const formatUserInfo = (openid: string, nickName?: string): string => {
  if (nickName) {
    return `${nickName} (${openid})`
  }
  return openid
}

// 验证购物车项数据
export const validateCartItem = (item: CartItem): boolean => {
  return !!(item.openid && item.productId && item.quantity > 0 && item.price >= 0)
}

// 计算购物车统计信息
export const calculateCartStats = (items: CartItem[]) => {
  const stats = {
    totalItems: items.length,
    activeItems: items.filter((item) => item.status === 'active').length,
    inactiveItems: items.filter((item) => item.status === 'inactive').length,
    expiredItems: items.filter((item) => item.status === 'expired').length,
    totalQuantity: items.reduce((sum, item) => sum + item.quantity, 0),
    totalAmount: items.reduce(
      (sum, item) => sum + calculateTotalAmount(item.price, item.quantity),
      0
    ),
    uniqueUsers: [...new Set(items.map((item) => item.openid))].length,
    uniqueProducts: [...new Set(items.map((item) => item.productId))].length
  }

  return {
    ...stats,
    avgItemsPerUser:
      stats.uniqueUsers > 0 ? (stats.totalItems / stats.uniqueUsers).toFixed(2) : '0',
    avgQuantityPerItem:
      stats.totalItems > 0 ? (stats.totalQuantity / stats.totalItems).toFixed(2) : '0'
  }
}

// 过滤和搜索购物车项
export const filterCartItems = (items: CartItem[], filters: CartListParams): CartItem[] => {
  let filtered = [...items]

  if (filters.openid) {
    filtered = filtered.filter((item) => item.openid.includes(filters.openid!))
  }

  if (filters.productId) {
    filtered = filtered.filter((item) => item.productId === filters.productId)
  }

  if (filters.status) {
    filtered = filtered.filter((item) => item.status === filters.status)
  }

  if (filters.keyword) {
    const keyword = filters.keyword.toLowerCase()
    filtered = filtered.filter(
      (item) =>
        item.openid.toLowerCase().includes(keyword) ||
        item.product?.name.toLowerCase().includes(keyword)
    )
  }

  return filtered
}
